import copy
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from SecureHelperServer.settings import formatResponseData
from utils.conf import newBindCode, Response
from utils.custom import MyJWTAuthentication


class UpdateBindCodeView(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        个人中心-更新监护码
        """
        data = copy.deepcopy(formatResponseData)
        try:
            user = request.user
            bindCode = newBindCode()
            user.bindCode = bindCode
            user.save()

            data["data"]["bindCode"] = bindCode
            return Response(data=data, responseMsg="更新成功",
                            loggerMsg=f"更新监护码：更新成功: uid={user.uid}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
